﻿#include "QCefV8Handler.h"
#include "QCefRenderClient.h"


QCefV8Handler::QCefV8Handler(QCefRenderClient* client)
    : m_client(client)
{
    QCEF_DEBUG();
}


QCefV8Handler::~QCefV8Handler()
{
    QCEF_DEBUG();

    m_client = nullptr;
}


bool QCefV8Handler::Execute(const CefString& function,
                           CefRefPtr<CefV8Value> object,
                           const CefV8ValueList& arguments,
                           CefRefPtr<CefV8Value>& retval,
                           CefString& exception)
{
    QCEF_DEBUG();

    if (function == kQCefReportJavaScriptResultFunctionName)
    {
        return reportJavaScriptResult(object, arguments, retval, exception);
    }

    return true;
}

bool QCefV8Handler::reportJavaScriptResult(CefRefPtr<CefV8Value> object,
                                         const CefV8ValueList& arguments,
                                         CefRefPtr<CefV8Value>& retval,
                                         CefString& exception)
{
    QCEF_DEBUG();

    if (arguments.size() == 2)
    {
        if (arguments[0]->IsDouble())
        {
            m_client->reportJavaScriptResult(arguments);
        }
        else
        {
            exception = "Invalid argument; argument 1 must be a double";
        }
    }
    else
    {
        exception = "Invalid argument; expecting 2 argument";
    }

    retval = CefV8Value::CreateUndefined();

    return true;
}
